package com.ogawa.project6602.viewmodel

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadLargeFileListener
import com.liulishuo.filedownloader.FileDownloader
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.base.utils.FileUtils
import com.ogawa.musicmodule.*
import com.ogawa.musicmodule.bean.ChangeMusicAllTimeEvent
import com.ogawa.musicmodule.bean.PlayMainMusicEvent
import com.ogawa.musicmodule.bean.PlayMixMusicBean
import com.ogawa.project6602.R
import com.ogawa.project6602.activity.*
import com.ogawa.project6602.bean.MusicResponse
import com.ogawa.project6602.service.MusicApiService
import com.ogawa.projectcommon.appdatabase.AppDatabase
import com.ogawa.projectcommon.bean.MusicBean
import com.ogawa.projectcommon.bean.MusicMixCollectBean
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.projectcommon.utils.launch
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.lang.Exception


/**
 * notifListType: 0:脑波列表    1:混音播放列表    2:混音列表
 */
data class UpdateItemBean(val notifListType: Int, val index: Int)
class MusicViewModel : BaseViewModel() {
    var beanIndexValue = MutableLiveData<UpdateItemBean>()//第几个音乐
    val musicAllTimeObx = MutableLiveData<Float>()
    val downFileProgressStr = MutableLiveData<String>()
    val musicNaoBoAdapterBeans = MutableLiveData<List<MusicResponse>>()
    val musicHunYinAdapterBeans = MutableLiveData<List<MusicResponse>>()
    val mixMusicplayBeans = MutableLiveData<List<MusicResponse>>()
    var apiServiceMusicList = ArrayList<MusicResponse>()
    private val musicApi = RetrofitManager.INSTANCE.createService(MusicApiService::class.java)
    var fileDownloader: BaseDownloadTask? = null

    init {
        beanIndexValue.value = UpdateItemBean(0, 0)
    }


    fun getMusicList(context: Context) {
        launch({

            //设置时间
            val musicAllTime = MusicProjectSpUtils.getMusicAllTime()
            musicAllTimeObx.value = musicAllTime

            //本地查找收藏的混音
            val musicCollectDao = AppDatabase.get(context).getMixMusicCollectDao()
            val allMixCollectMusics = musicCollectDao.getAllMusic()
            var _playList = ArrayList<MusicResponse>()
            for (musicMixCollectBean in allMixCollectMusics){
                var _item = MusicResponse()
                if (!File(musicMixCollectBean.localpath).exists()){
                    musicCollectDao.deleteMusic(musicMixCollectBean)
                    continue
                }
                _item.name = musicMixCollectBean.name
                _item.downIcon = musicMixCollectBean.downIcon
                _item.path = musicMixCollectBean.localpath
                _item.status = MUSIC_STATUS_READY
                for (musicServiceMixBean in MusicService.playMixMusicBeans){
                    if (musicServiceMixBean.title == _item.name){
                        if (musicServiceMixBean.status == MUSIC_SERVER_STATUS_SUSPEND){
                            _item.status = MUSIC_STATUS_SUSPEND
                        }else if(musicServiceMixBean.status == MUSIC_SERVER_STATUS_PLAY_ING){
                            _item.status = MUSIC_STATUS_PLAY_ING
                        }else if(musicServiceMixBean.status == MUSIC_SERVER_STATUS_PLAY_RELAY){
                            _item.status = MUSIC_STATUS_READY
                        }
                    }
                }
                _playList.add(_item)
            }
            try {
                _playList = _playList.subList(0,3) as ArrayList<MusicResponse>
            }catch (e:Exception){
                e.printStackTrace()
            }
            var emptyCount = 3-_playList.size
            if (emptyCount > 0){
                for (i in _playList.size..3-1){
                    var _item = MusicResponse()
                    _item.name = "${i+1}模式"
                    _item.status = MUSIC_STATUS_EMPTY
                    _playList.add(_item)
                }
            }

            mixMusicplayBeans.value = _playList




            //获取网络数据
            loadState.value = LoadState.Loading("")
            var musicList = musicApi.getDeviceStatus("", "")
            loadState.value = LoadState.Success("")
            apiServiceMusicList.clear()
            apiServiceMusicList.addAll(musicList.data)
            var _musicNaoBoBeans = ArrayList<MusicResponse>()
            var _MusicHunYinBeans = ArrayList<MusicResponse>()
            for (item in musicList.data) {
                if (item.categoryCode == "brainWaveAudio") {
                    _musicNaoBoBeans.add(item)
                } else if (item.categoryCode == "whiteNoise") {
                    _MusicHunYinBeans.add(item)
                }
            }
            val musicDao = AppDatabase.get(context).getMusicDao()
            val musics = musicDao.getAllMusic()
            for (musicNaoboBean in _musicNaoBoBeans) {
                musicNaoboBean.status = MUSIC_STATUS_WAIT_DOWN
                for (music in musics) {
                    if (musicNaoboBean.name == music.name) {
                        if (musicNaoboBean.downUrl == music.url) {
                            musicNaoboBean.status = MUSIC_STATUS_SUSPEND
                            musicNaoboBean.path = music.localpath
                            if (musicNaoboBean.name == MusicService.playMainMusicBean.title){
                                musicNaoboBean.isLast = true
                                if (MusicService.playMainMusicBean.status == MUSIC_SERVER_STATUS_SUSPEND){
                                    musicNaoboBean.status = MUSIC_STATUS_SUSPEND
                                }else if(MusicService.playMainMusicBean.status == MUSIC_SERVER_STATUS_PLAY_ING){
                                    musicNaoboBean.status = MUSIC_STATUS_PLAY_ING
                                }
                            }
                        } else {//如果url不一样，就替换
                            musicDao.deleteMusic(music)
                            musicNaoboBean.status = MUSIC_STATUS_WAIT_DOWN
                        }
                    }
                }
            }
            musicNaoBoAdapterBeans.value = _musicNaoBoBeans

            for (item in _MusicHunYinBeans) {
                item.status = MUSIC_STATUS_WAIT_DOWN
                for (music in musics) {
                    if (item.name == music.name) {
                        if (item.downUrl == music.url) {
                            item.status = MUSIC_STATUS_SUSPEND
                            item.path = music.localpath
                        } else {//如果url不一样，就替换
                            musicDao.deleteMusic(music)
                            item.status = MUSIC_STATUS_WAIT_DOWN
                        }
                    }
                }
            }
            musicHunYinAdapterBeans.value = _MusicHunYinBeans


        }, { loadState.value = LoadState.Fail(it.message ?: "") }, {})

    }


    fun searchHunyin(key:String){
        var _list = ArrayList<MusicResponse>()
        for (item in apiServiceMusicList){
            if (item.categoryCode == "whiteNoise" && item.name.contains(key)){
                _list.add(item)
            }
        }
        musicHunYinAdapterBeans.value = _list
    }


    /**
     * 添加混音
     */
    fun addHunYin(context: Context,index: Int) {
        val musicResponse = musicHunYinAdapterBeans.value?.get(index)
        mixMusicplayBeans.value?.let {
            val musicCollectDao = AppDatabase.get(context).getMixMusicCollectDao()
            for (item in it){
                if (item.name == musicResponse!!.name){
                    ToastUtils.showShort("已存在")
                    return
                }
            }
            var changeIndex = -1

            for (musicPlayindex in it.indices){
                val item = it[musicPlayindex]
                if (item.status == MUSIC_STATUS_EMPTY){
                    changeIndex = musicPlayindex
                    break
                }
            }
            if (changeIndex == -1){
                for (musicPlayindex in it.indices){
                    val item = it[musicPlayindex]
                    if (item.status == MUSIC_STATUS_READY|| item.status == MUSIC_STATUS_SUSPEND){
                        changeIndex = musicPlayindex
                        break
                    }
                }
            }
            //如果以上规则都不匹配，就替换第一个
            if (changeIndex == -1){
                changeIndex = 0
            }
            if (changeIndex == -1){
                ToastUtils.showShort("暂无可替换位置")
                return
            }
            beanIndexValue.value = UpdateItemBean(1, -1)

            val item = it[changeIndex]
            if (
                item.status == MUSIC_STATUS_EMPTY
                || item.status == MUSIC_STATUS_PLAY_ING
                || item.status == MUSIC_STATUS_READY
                || item.status == MUSIC_STATUS_SUSPEND
            ){
                item.name = musicResponse?.name
                item.downUrl = musicResponse?.downUrl
                item.downIcon = musicResponse?.downIcon
                item.status = MUSIC_STATUS_READY
                item.path = musicResponse?.path
                item.id = musicResponse?.id!!
                item.categoryCode = musicResponse.categoryCode

                var musicCollectBean = MusicMixCollectBean()
                musicCollectBean.localpath = item.path
                musicCollectBean.downIcon = item.downIcon
                musicCollectBean.status = item.status
                musicCollectBean.id = item.id
                musicCollectBean.name = item.name
                musicCollectBean.url = item.downUrl
                musicCollectBean.position = changeIndex
                musicCollectDao.insert(musicCollectBean)
                EventBus.getDefault().post(musicCollectBean)
            }
        }



    }


    /**
     * 取消下载音乐
     */
    fun cancelDownMusicFile() {
        if (fileDownloader?.isRunning == true) {
            fileDownloader?.pause()
        }
        fileDownloader = null
    }

    fun downMusicFile(
        context: Context,
        url: String,
        name: String,
        isNaoBoBean: Boolean,
        beanIndex: Int
    ) {
        var pathStr = FileUtils.getExternalFilesDir(context) + name
        launch({
            downFileProgressStr.value = "0%"
            FileDownloader.setup(context)
            fileDownloader = FileDownloader.getImpl().create(url)
                .setPath(pathStr)
                .setListener(object : FileDownloadLargeFileListener() {
                    override fun pending(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                    }

                    override fun progress(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                        val progress = (soFarBytes * 100 / totalBytes).toInt()
                        if (progress < 100) {
                            downFileProgressStr.value = "$progress%"
                        } else {
                            downFileProgressStr.value = ""
                        }
                    }

                    override fun paused(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                    }

                    override fun completed(task: BaseDownloadTask) {
                        launch({
                            downFileProgressStr.value = ""
                            ToastUtils.showShort("下载完成")
                            val musicDao = AppDatabase.get(context).getMusicDao()
                            var musicBean = MusicBean()
                            musicBean.localpath = task.path
                            musicBean.url = task.url
                            musicBean.name = name
                            musicDao.insert(musicBean)

                            if (isNaoBoBean) {
                                musicNaoBoAdapterBeans.value?.get(beanIndex)?.let {
                                    it.status = MUSIC_STATUS_SUSPEND
                                    it.path = task.path
                                }
                            } else {
                                musicHunYinAdapterBeans.value?.get(beanIndex)?.let {
                                    it.status = MUSIC_STATUS_SUSPEND
                                    it.path = task.path
                                }
                            }
                            beanIndexValue.value = UpdateItemBean(if(isNaoBoBean){0}else{2}, beanIndex)

                        })
                    }

                    override fun error(task: BaseDownloadTask, e: Throwable) {
                        downFileProgressStr.value = ""
                        ToastUtils.showShort(context.getString(R.string.check_update_file_down_err))
                    }

                    override fun warn(task: BaseDownloadTask) {}
                })
            fileDownloader!!.start()

        })
    }


    /**
     * 重新开始全部
     */
    fun startAllMusic(context: Context){
        var naoboLastIndex = -1
        musicNaoBoAdapterBeans.value?.let { musicNaoBoBeanList->
            for(naoboIndex in musicNaoBoBeanList.indices){
                val lastNaobomusicResponse = musicNaoBoBeanList[naoboIndex]
                if (lastNaobomusicResponse.isLast && (
                            lastNaobomusicResponse.status == MUSIC_STATUS_SUSPEND
                        )){
                    naoboLastIndex = naoboIndex
                }
            }
        }
        if (naoboLastIndex >=0){
            changeNaoBoMusic(context,naoboLastIndex)
        }

        mixMusicplayBeans.value?.let {
            for(index in it.indices){
                val mixmusicResponse = it[index]
//                if (mixmusicResponse.status == MUSIC_STATUS_SUSPEND){
                if (mixmusicResponse.status == MUSIC_STATUS_SUSPEND||mixmusicResponse.status == MUSIC_STATUS_READY){
                    chnagePlayMix(context,index)
                }

            }
        }
    }

    /**
     * 停止播放音乐
     */
    fun stopAllMusic(context: Context) {
        val musicCollectDao = AppDatabase.get(context).getMixMusicCollectDao()
        var lastBean : MusicResponse?=null
        musicNaoBoAdapterBeans.value?.let { list ->
            for (pos in list.indices) {
                var item = list[pos]
                if (item.isLast){
                    lastBean = item
                }
                if (item.status != MUSIC_STATUS_WAIT_DOWN) {
                    item.status = MUSIC_STATUS_SUSPEND
                }
            }
            if (lastBean != null){
                EventBus.getDefault().post(PlayMainMusicEvent(lastBean!!.name, "", MUSIC_SERVER_STATUS_SUSPEND))
            }else{
                EventBus.getDefault().post(PlayMainMusicEvent("", "", MUSIC_SERVER_STATUS_SUSPEND))
            }
        }
        mixMusicplayBeans.value?.let {
            for (index in it.indices){
                var item = it[index]
//                if (item.status != MUSIC_STATUS_EMPTY){
                if (item.status == MUSIC_STATUS_PLAY_ING){
                    item.status = MUSIC_STATUS_SUSPEND
//                    val get = musicCollectDao.getAllMusic().get(index)
//                    get.status = MUSIC_STATUS_SUSPEND
//                    musicCollectDao.insert(get)
                }
                EventBus.getDefault().post(PlayMixMusicBean(item.name, item.path, MUSIC_SERVER_STATUS_SUSPEND,index))
            }
        }
        beanIndexValue.value = UpdateItemBean(0, -1)
        beanIndexValue.value = UpdateItemBean(1, -1)
    }


    /**
     * 播放混音
     */
    fun chnagePlayMix(context: Context, index: Int){
        val musicBean = mixMusicplayBeans.value?.get(index)
        musicBean?.let {
            if (musicBean.status == MUSIC_STATUS_EMPTY){
                return
            }
            var playMixMusicBean = PlayMixMusicBean(musicBean.name,musicBean.path,musicBean.status,index)
            if (musicBean.status == MUSIC_STATUS_PLAY_ING){
                musicBean.status = MUSIC_STATUS_SUSPEND
                playMixMusicBean.status = MUSIC_STATUS_SUSPEND
            }else{
                musicBean.status = MUSIC_STATUS_PLAY_ING
                playMixMusicBean.status = MUSIC_STATUS_PLAY_ING
            }
            EventBus.getDefault().post(playMixMusicBean)
            beanIndexValue.value = UpdateItemBean(1, -1)
        }

    }

    /**
     * 播放脑波音乐
     */
    fun changeNaoBoMusic(context: Context, index: Int) {
        musicNaoBoAdapterBeans.value?.let { list ->
            for (pos in list.indices) {
                var item = list[pos]
                if (pos != index) {
                    item.isLast = false
                    if (item.status != MUSIC_STATUS_WAIT_DOWN) {
                        item.status = MUSIC_STATUS_SUSPEND
                    }
                }
            }
            val bean = list[index]
            bean.let {
                if (it.status == MUSIC_STATUS_SUSPEND) {
                    it.status = MUSIC_STATUS_PLAY_ING
//                    EventBus.getDefault().post(PlayMainMusicBean("","",MUSIC_SERVER_STATUS_SUSPEND))
                    if (!it.isLast) {
                        EventBus.getDefault()
                            .post(PlayMainMusicEvent(bean.name, it.path, MUSIC_SERVER_STATUS_PLAY_ING))
                        ToastUtils.showShort("重新播放")
                    } else {
                        EventBus.getDefault()
                            .post(PlayMainMusicEvent(bean.name, it.path, MUSIC_SERVER_STATUS_PLAY_ING))
                        ToastUtils.showShort("继续播放")
                    }
                } else if (it.status == MUSIC_STATUS_PLAY_ING) {
                    it.status = MUSIC_STATUS_SUSPEND
                    EventBus.getDefault()
                        .post(PlayMainMusicEvent(bean.name, it.path, MUSIC_SERVER_STATUS_SUSPEND))
                }
                it.isLast = true
                beanIndexValue.value = UpdateItemBean(0, -1)



            }


        }
    }


    fun changeAllTime(){
        val value = musicAllTimeObx.value
        val timeList = ArrayList<Float>()
        timeList.add(10 * 60f)
        timeList.add(15 * 60f)
        timeList.add(20 * 60f)
        timeList.add(30 * 60f)
        timeList.add(60 * 60f)
        var nextIndex = 0
        for (index in timeList.indices){
            if (timeList[index] == value){
                nextIndex = index+1
            }
        }
        if (nextIndex>=timeList.size ){
            nextIndex = 0
        }
        musicAllTimeObx.value = timeList[nextIndex]
        MusicProjectSpUtils.setMusicAllTime(timeList[nextIndex])
        EventBus.getDefault().post(ChangeMusicAllTimeEvent())
    }


}